﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using GameLogic.Controls;

namespace ColorReminder.Phone
{
	public partial class ColorReminderGame : UserControl, IGameFeatures
	{
		public ColorReminderGame()
		{
			// Required to initialize variables
			InitializeComponent();
		}

        public event EventHandler<ScoresChangedEventArgs> ScoresChanged;
        public event EventHandler<TimeChangedEventArgs> TimeChanged;
        public event EventHandler<LivesChangedEventArgs> LivesChanged;

        public event EventHandler PauseTimerFired;

        public event EventHandler ResumeTimerFired;


        public void Start()
        {
            _message.Text = "Let's go";
            _showMessage.Completed += _showStartMessage_Completed;
            _showMessage.Begin();
        }

        public void Stop()
        {
            //throw new NotImplementedException();
        }

        public void Pause()
        {
            //throw new NotImplementedException();
        }

        public void Resume()
        {
            //throw new NotImplementedException();
        }

        public void ChangeScores(int value)
        {

        }

        public void ChangeLives(int value)
        {

        }

        //public void GameOver(GameOverEventArgs args)
        //{
        //    throw new NotImplementedException();
        //}

        public bool IsTimeBased
        {
            get { return false; }
        }

        public bool IsLifeBased
        {
            get { return false; }
        }

        public string GameName
        {
            get { return "Color Reminder"; }
        }

        List<int> _gameValues;
        int _round;
        Random _rnd = new Random();
        int _currentValue;

        //private void _startButton_Click(object sender, RoutedEventArgs e)
        //{
        //    _message.Text = "Let's go";
        //    _showMessage.Completed += _showStartMessage_Completed;
        //    _showMessage.Begin();
        //}

        void _showStartMessage_Completed(object sender, EventArgs e)
        {
            _showMessage.Completed -= _showStartMessage_Completed;
            StartGame();
        }

        private void StartGame()
        {
            VisualStateManager.GoToState(this, "GameScreenState", false);

            OnScoresChanged(0);
            _gameValues = new List<int>();
            _round = 0;

            DoRound(_round++);
        }

        private void DoRound(int p)
        {
            _gameValues.Add(_rnd.Next(4));
            _currentValue = 0;
            ShowValues();
        }

        private void ShowValues()
        {
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 1);
            timer.Tick += (s, e) =>
            {
                timer.Stop();
                ShowValue(_currentValue);
            };
            timer.Start();
        }

        private void ShowValue(int _round)
        {
            Bumper currentBumper;
            switch (_gameValues[_currentValue])
            {
                case 0:
                    currentBumper = _bumper0;
                    break;

                case 1:
                    currentBumper = _bumper1;
                    break;

                case 2:
                    currentBumper = _bumper2;
                    break;

                case 3:
                    currentBumper = _bumper3;
                    break;

                default:
                    throw new Exception("No bumper defined");
            }
            currentBumper.HighlightFinished += currentBumper_HighlightFinished;
            currentBumper.Highlight();
        }

        void currentBumper_HighlightFinished(object sender, EventArgs e)
        {
            Bumper b = sender as Bumper;
            b.HighlightFinished -= currentBumper_HighlightFinished;

            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 0, 0, 250);
            timer.Tick += (s, e1) =>
            {
                timer.Stop();
                ShowNextValue();
            };
            timer.Start();
        }

        private void ShowNextValue()
        {
            if (_currentValue < _gameValues.Count - 1)
            {
                ShowValue(_currentValue++);
            }
            else
            {
                StartPlayerTask();
            }
        }

        private void StartPlayerTask()
        {
            _currentValue = 0;

            _bumper0.MouseLeftButtonDown += _bumper_MouseLeftButtonDown;
            _bumper1.MouseLeftButtonDown += _bumper_MouseLeftButtonDown;
            _bumper2.MouseLeftButtonDown += _bumper_MouseLeftButtonDown;
            _bumper3.MouseLeftButtonDown += _bumper_MouseLeftButtonDown;
        }

        void _bumper_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Bumper bumper = sender as Bumper;
            bumper.HighlightFinished += (s, e1) =>
            {

            };
            bumper.Highlight();

            // Check if user is right
            int correctValue = _gameValues[_currentValue];

            // selected bumber
            int bumperValue;
            if (sender == _bumper0)
            {
                bumperValue = 0;
            }
            else if (sender == _bumper1)
            {
                bumperValue = 1;
            }
            else if (sender == _bumper2)
            {
                bumperValue = 2;
            }
            else if (sender == _bumper3)
            {
                bumperValue = 3;
            }
            else
            {
                throw new Exception("Unexpected value");
            }

            if (correctValue == bumperValue)
            {
                // User is right
                _currentValue++;

                if (_currentValue >= _gameValues.Count)
                {
                    _bumper0.MouseLeftButtonDown -= _bumper_MouseLeftButtonDown;
                    _bumper1.MouseLeftButtonDown -= _bumper_MouseLeftButtonDown;
                    _bumper2.MouseLeftButtonDown -= _bumper_MouseLeftButtonDown;
                    _bumper3.MouseLeftButtonDown -= _bumper_MouseLeftButtonDown;

                    NextRound();
                }
            }
            else
            {
                _bumper0.MouseLeftButtonDown -= _bumper_MouseLeftButtonDown;
                _bumper1.MouseLeftButtonDown -= _bumper_MouseLeftButtonDown;
                _bumper2.MouseLeftButtonDown -= _bumper_MouseLeftButtonDown;
                _bumper3.MouseLeftButtonDown -= _bumper_MouseLeftButtonDown;

                PlayerLose();
            }
        }

        private void NextRound()
        {
            OnScoresChanged(_round);

            _round++;
            _message.Text = "Round: " + _round.ToString();
            _showMessage.Completed += _showNextRoundMessage_Completed;
            _showMessage.Begin();
        }


       
        public void OnLivesChanged(int lives)
        {
            throw new NotImplementedException();
        }

        public void OnScoresChanged(int scores)
        {
            if (ScoresChanged != null)
            {
                ScoresChangedEventArgs args = new ScoresChangedEventArgs();
                args.Scores = scores;
                ScoresChanged(this, args);
            }
        }

        void _showNextRoundMessage_Completed(object sender, EventArgs e)
        {
            _showMessage.Completed -= _showNextRoundMessage_Completed;

            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 1);
            timer.Tick += (s, e1) =>
            {
                timer.Stop();
                DoRound(_round);
            };
            timer.Start();
        }

        private void PlayerLose()
        {
            _message.Text = "You lose.";
            _showMessage.Begin();
            _playGround.Visibility = System.Windows.Visibility.Collapsed;
            if (GameOver != null)
            {
                GameOverEventArgs args = new GameOverEventArgs();
                args.Message = "You lose.";
                GameOver(this, args);
            }
        }



        public TimeSpan GameDuration
        {
            get { throw new NotImplementedException(); }
        }


        public event EventHandler<GameOverEventArgs> GameOver;

        public string DeveloperName
        {
            get { return "Oliver Scheer"; }
        }

        public string CompanyName
        {
            get { return "Microsoft Deutschland"; }
        }

        public string Description
        {
            get { return string.Empty; }
        }

        public Uri SettingsPage
        {
            get { return null; }
        }

   }
}